package Utils

import (
	"fmt"
	"io/ioutil"
	"os"
	"strings"
)

func IsExist(f string) bool {
	_, err := os.Stat(f)
	return err == nil || os.IsExist(err)
}

func IsFile(f string) bool {
	fi, e := os.Stat(f)
	if e != nil {
		return false
	}
	return !fi.IsDir()
}

func IsDir(f string) bool {
	return !IsFile(f)
}

func GetFileBlock(filePath string, blockSize int64) []byte {
	file, err := os.OpenFile(filePath, os.O_RDONLY, 0666)
	if err != nil {
		fmt.Println("打开文件错误!", err)
		return nil
	}
	defer file.Close()
	stat, err := file.Stat()
	if err != nil {
		panic(err)
	}
	size := stat.Size()
	newBlockSize := blockSize
	if newBlockSize == 0 {
		newBlockSize = size
	}
	newBlockSize = MinInt64(size, newBlockSize)
	buf := make([]byte, newBlockSize)

	_, err = file.Read(buf)
	return buf
}

func GetFileBytes(filePath string, offset int64, blockSize int64) []byte{
	file, err := os.OpenFile(filePath, os.O_RDONLY, 0666)
	if err != nil {
		fmt.Println("打开文件错误!", err)
		return nil
	}
	defer file.Close()
	stat, err := file.Stat()
	if err != nil {
		panic(err)
	}
	size := stat.Size()
	newBlockSize := blockSize
	if newBlockSize == 0 {
		newBlockSize = size - offset
	}
	buf := make([]byte, newBlockSize)
	_, err = file.ReadAt(buf, offset)
	return buf
}

type FileInfo struct {
	FilePath string
	Len int64
	FileName string
	Ext string
}

func GetFileInfo(p string) *FileInfo {
	fs, err := os.Stat(p)
	if err != nil {
		return nil
	}
	return &FileInfo{
		FilePath: p,
		Len: fs.Size(),
		FileName: fs.Name(),
		Ext: GetFileNameExt(fs.Name()),
	}
}

func GetFiles(dirPath string, scanAll bool, filterStr string) []FileInfo {
	result := make([]FileInfo, 0)
	tDirPath := AddPathSeparator(dirPath)
	fs, _ := ioutil.ReadDir(tDirPath)
	filters := make([]string, 0)
	if filterStr != "" {
		filters = strings.Split(filterStr+"|", "|")
	}
	addPd := false
	for _, file := range fs {
		if len(filters) > 0 {
			addPd = false
			for _, filter := range filters {
				if filter == ""{
					continue
				}
				if strings.HasSuffix(file.Name(), filter){
					addPd = true
					break
				}
			}
		}
		if !addPd{
			continue
		}
		if file.IsDir() {
			if scanAll {
				result = append(result, GetFiles(tDirPath+file.Name(), scanAll, filterStr)...)
			}
		} else {
			result = append(result, FileInfo{
				FilePath: tDirPath+file.Name(),
				Len: file.Size(),
				FileName: file.Name(),
				Ext: GetFileNameExt(file.Name()),
			} )
		}
	}
	return result
}
